import React, { useState, useMemo, useEffect } from 'react';
import { uJob, InfoDlg, uDb, cline, obj_str, no_del, useHigh, GridTable, filter_row, useCmd, WaitUmd, MainView, BtTxt, PanelFind, loc } from 'sui';
import { PsnView } from './psn';
import { useAccess } from 'cache';
import { reload_order } from './cmd';

const OrderView = () => {
    const [open_info, openInfo] = useState(false);
    const [main, setMain] = useState();
    const [high] = useHigh(140, 100);
    const [no_acc] = useAccess();
    const umd = useCmd();

    useEffect(() => {
        reload_order(null, setMain);
    }, []);

    const getRow = useMemo(() => {
        const lst = ["sn"];
        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter]);

    const hret = () => {
        reload_order(null, setMain);
        umd.hreturn();
    };

    if (umd.isFin("psn")) {
        return <PsnView cur={umd.cur} hreturn={hret}/>;
    }

    const hfin = () => {
        const sn = obj_str(umd.cur, "sn");
        if (!sn) {
            return;
        }

        umd.startWait();

        uJob(null, "goods/fin",
            {
                line: cline(),
                k: sn,
            },
            r => reload_order(umd.endWait, setMain),
            e => umd.setErr());
    };

    const pact = {
        "fin": () => openInfo(true),
    };

    const hdel = (v) => {
        if (no_del()) {
            return;
        }

        umd.startWait();

        uDb(null, "file/rm/gorder",
            {
                line: cline(),
                sn: obj_str(v, "sn"),
            },
            r => reload_order(umd.endWait, setMain),
            e => umd.setErr());
    };

    const col = [
        {name: loc("l_193"), key: 'index', width: 70},
        {name: loc("l_176"), key: 'sn', width: 160},
        {name: loc("l_238"), key: 'e_opt', width: 204, export: false, formatter: props => {
            const d = props.row;
            return (
                <div className="inline-flex">
                    <BtTxt hcmd={() => hdel(d)} disabled={no_acc("nb")}>{loc("l_237")}</BtTxt>
                    <BtTxt hcmd={() => umd.pact(null, d, "psn")} disabled={no_acc("nb")}>{loc("l_469")}</BtTxt>
                    <BtTxt hcmd={() => umd.pact(pact, d, "fin")} disabled={no_acc("nb")}>{loc("l_858")}</BtTxt>
                </div>
            );
        }},
        {name: loc("l_177"), key: 'tech', width: 160},
        {name: loc("l_127"), key: 'num', width: 160},
        {name: loc("l_856"), key: 'dnum', width: 160},
    ];

    return (
        <MainView>
            <PanelFind left={loc("l_852")} hcmd={v => umd.setFilter(v)}/>
            <GridTable col={col} row={getRow} high={high}/>
            <WaitUmd umd={umd}/>
            <InfoDlg open={open_info} setOpen={openInfo} msg={loc("l_859")} hcmd={hfin} hcancel={() => openInfo(false)}/>
        </MainView>
    );
};

export {OrderView};
